package com.objcat.playground.leetcode;

import java.util.ArrayList;

public class Solution21 {

    /**
     * description: reverseList <br>
     * version: 1.0 <br>
     * date: 2022/3/14 1:12 PM <br>
     * author: objcat <br>
     * 执行用时：19 ms, 在所有 Java 提交中击败了 100.00% 的用户
     * 内存消耗：41.2 MB, 在所有 Java 提交中击败了 24.44% 的用户
     * @param head 节点头
     * @return 节点头
     */
    public ListNode reverseList(ListNode head) {
        // 判断边界
        if (head == null || head.next == null) {
            return head;
        }
        // 求数量
        int count = 0;
        ListNode node2 = head;
        while (true) {
            count++;
            if (node2.next == null) {
                break;
            }
            node2 = node2.next;
        }
        // 遍历1/2次数组就能完成翻转
        for (int i = 0; i < count / 2; i++) {
            // 获取需要交换的节点
            ListNode a = this.index(head, i);
            ListNode b = this.index(head, count - 1 - i);
            // 交换值
            int temp = a.val;
            a.val = b.val;
            b.val = temp;
        }
        return head;
    }

    public ListNode index(ListNode head, int index) {
        for (int i = 0; i < index; i++) {
            head = head.next;
        }
        return head;
    }

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
//        list.add(3);
//        list.add(4);

        ListNode head = ListNode.createNode(list);
        Solution21 solution21 = new Solution21();
        head = solution21.reverseList(head);
    }
}

